﻿using Application.Common.Behaviours;
using Application.Commons.Behaviours;
using Common.Behaviours;
using Common.PublishStrategies;
using FluentValidation;
using MediatR;
using MediatR.Pipeline;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Application;

public static class MediatRExtensions
{
    public static IServiceCollection AddDefaultApplicationServices(this IServiceCollection services)
    {
        #region FluentValidation 服务
        services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());
        #endregion

        #region MediatR 服务
        services.AddMediatR(config => {
            var aaa = Assembly.GetExecutingAssembly();
            config.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
            config.NotificationPublisher = new ParallelNoWaitPublisher();
            config.AddOpenBehavior(typeof(UnhandledExceptionBehaviour<,>));
            config.AddOpenBehavior(typeof(RequestExceptionProcessorBehavior<,>));
            config.AddOpenBehavior(typeof(AuthorizationBehaviour<,>));
            config.AddOpenBehavior(typeof(ValidationBehaviour<,>));
            //config.AddOpenBehavior(typeof(CacheBehaviour<,>));
            //config.AddOpenBehavior(typeof(CacheInvalidationBehaviour<,>));
            services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TransactionBehavior<,>));
        });
        #endregion

        return services;
    }
}
